package com.bestom.rideelectric.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.bestom.rideelectric.Entity.Constant;
import com.bestom.rideelectric.R;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

public class MainActivity extends BaseActivity implements SurfaceHolder.Callback {

    /**记录连续点击次数，五秒内无点击则恢复初始值 0*/
    private int clickBleNum = 0;
    private int clickFileNum = 0;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        //初始化组件
        initView();
        //初始化数据
        initData();
        //发送广播给系统计时
        sendBroadcastToSystemTime();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoList != null) {
            videoList.clear();
            videoList = getVideoFileName("mnt/sdcard/Movies/");
            mHandler.postDelayed(this::nextVideo,1000);
//            nextVideo();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mMediaPlayer.isPlaying()) mMediaPlayer.stop();
    }

    private void sendBroadcastToSystemTime() {
        Intent intent1 = new Intent(Constant.To_Monitor_User_Operation);
        sendBroadcast(intent1);
    }

    private SurfaceView mSurfaceView;
    private SurfaceHolder surfaceHolder;
    private MediaPlayer mMediaPlayer;
    private void initView() {
        findViewById(R.id.go_blue).setOnClickListener(v -> {
            clickBleNum++;
            if (clickBleNum == 5){
                clickBleNum = 0;
                mHandler.removeCallbacks(mRunnable);
                new AlertDialog.Builder(mContext)
                        .setTitle("配置蓝牙")
                        .setMessage("是否前往配置蓝牙连接？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            mMediaPlayer.stop();
                            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
//                                intent.putExtra(":settings:show_fragment_as_subsetting", true);
                            startActivityForResult(intent,1);
                        })
                        .setNegativeButton("取消", null)
                        .setOnDismissListener(dialog -> hideBottomUIMenu())
                        .show();
            }else {
                mHandler.sendEmptyMessage(0);
            }
        });
        findViewById(R.id.go_file).setOnClickListener(v -> {
            clickFileNum++;
            if (clickFileNum == 5){
                clickFileNum = 0;
                mHandler.removeCallbacks(mRunnable);
                new AlertDialog.Builder(mContext)
                        .setTitle("文件管理")
                        .setMessage("是否前往文件管理界面？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            /*mMediaPlayer.stop();
                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setType("file/*");
                            intent.putExtra(":settings:show_fragment_as_subsetting", true);
                            startActivity(intent);*/
                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            ComponentName cn = new ComponentName("com.android.rk", "com.android.rk.RockExplorer");
                            intent.setComponent(cn);
                            intent.putExtra(":settings:show_fragment_as_subsetting", true);
                            startActivityForResult(intent, 123);
                        })
                        .setNegativeButton("取消", null)
                        .setOnDismissListener(dialog -> hideBottomUIMenu())
                        .show();
            }else {
                mHandler.sendEmptyMessage(0);
            }
        });
        mSurfaceView = findViewById(R.id.video_sv);
    }

    private void initData() {
        surfaceHolder = mSurfaceView.getHolder();  //SurfaceHolder是SurfaceView的控制接口
        surfaceHolder.addCallback(this);  //因为这个类实现了SurfaceHolder.Callback接口，所以回调参数直接this
        //surfaceHolder.setFixedSize(320, 220);  //显示的分辨率,不设置为视频默认
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  //Surface类型
    }

    private void setListener() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setDisplay(surfaceHolder);

        // 加载完成事件
        mMediaPlayer.setOnPreparedListener(mp -> mMediaPlayer.start());
        // 播放完毕事件
        mMediaPlayer.setOnCompletionListener(mp -> {
            // 循环播放
            nextVideo();
        });
        // 播放异常事件
        mMediaPlayer.setOnErrorListener((mediaPlayer, arg1, arg2) -> {
            Log.d("onError","检测到错误，重新播放视频！");
            /*mMediaPlayer.reset();
            String uri = "android.resource://" + getPackageName() + "/" + R.raw.test;

            try {
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(uri));
                mMediaPlayer.prepareAsync();
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            return true;
        });

        //设置显示视频显示在SurfaceView上
//        String uri = "android.resource://" + getPackageName() + "/" + R.raw.test;
        videoList = getVideoFileName("mnt/sdcard/Movies/");
        nextVideo();

    }
    private Vector<String> videoList;
    private int count = 0;
    private void nextVideo() {

        if (videoList == null || videoList.size() == 0) {
            Toast.makeText(getApplicationContext(),"未检测到新视频，当前转换播放默认视频。",Toast.LENGTH_LONG).show();
            mMediaPlayer.reset();
            String uri = "android.resource://" + getPackageName() + "/" + R.raw.test;

            try {
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(uri));
                mMediaPlayer.prepareAsync();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        //表示已经全部播放完毕,重新播放让count变成0即可
        if (count >= videoList.size()) count = 0;

        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource("mnt/sdcard/Movies/" + videoList.get(count).trim());
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
            nextVideo();
        }
        count++;
    }

    // 获取当前目录下所有的mp4文件
    public Vector<String> getVideoFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();

        if (subFile != null) {
            for (File value : subFile) {
                // 判断是否为文件夹
                if (!value.isDirectory()) {
                    String filename = value.getName();
                    // 判断是否为MP4结尾
                    if (filename.trim().toLowerCase().endsWith(".mp4")) {
                        vecFile.add(filename);
                    }
                }
            }
        }
        return vecFile;
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        //必须在surface创建后才能初始化MediaPlayer,否则不会显示图像
        //设置监听
        surfaceHolder = holder;
        setListener();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            mHandler.removeCallbacks(mRunnable);
            mHandler.postDelayed(mRunnable,5000);
        }
    };

    private final Runnable mRunnable = () -> {
        clickBleNum = 0;
        clickFileNum = 0;
    };

    /**隐藏底部导航栏*/
    protected void hideBottomUIMenu() {
        int flags;
        int curApiVersion = android.os.Build.VERSION.SDK_INT;
        // This work only for android 4.4+
        if(curApiVersion >= Build.VERSION_CODES.KITKAT){

            // This work only for android 4.4+
            // hide navigation bar permanently in android activity
            // touch the screen, the navigation bar will not show

            flags = View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;

        }else{
            // touch the screen, the navigation bar will show
            flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }

        // must be executed in main thread :)
        getWindow().getDecorView().setSystemUiVisibility(flags);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
        }
        //Activity销毁时停止播放，释放资源。不做这个操作，即使退出还是能听到视频播放的声音
        mMediaPlayer.release();
    }
}